<template>
  <div v-loading="pageLoading" :class="{'mobile-create': showMobilePage}" class="adjustment-create-wrap">
    <explanation :explanation="explanationObj" is-expand style="margin: 0;"/>
    <div :class="{'pb55':device!=='mobile'}" class="page-container">
      <!-- 申请信息 -->
      <applyInfo ref="applyInfoRef" :detail-data="applyInfo" @onRangeChange="onRangeChange" />
      <!-- 当前客户信息 -->
      <customerInfo ref="customerInfoRef" :client-id="clientId" :default-customer-name="defaultCustomerName" @setClientInfo="setClientInfo" />
      <!-- 申请调整内容 -->
      <adjustContent ref="adjustContentRef" :range-list="rangeList" :detail-data="adjustContent" @update="queryAdjustedInfo" />
      <!-- 调整后客户信息 -->
      <adjustedInfo ref="adjustedInfoRef" :detail-data="adjustedInfo" :loading="adjustLoading" />
      <audit-process
        ref="auditProcess"
        :loading="loading"
        v-model="auditInfo"
        :old-audit-info="oldAuditInfo"
        :default-aduitor-list="[applyInfo.proposerObj]"

        :flow-structure="processDetail"
        :is-modify="Boolean(remodifyId)"
        :disable="Boolean(remodifyId)"
        :is-modify-form="Number(isModifyForm)"
        :current-process-index="Number(currentProcessIndex)"
        @submit="submit(SUBMIT_TYPE.SUBMIT,$event)"
        @getProcess="getProcess" />
      <fixed-pagination>
        <div class="center">
          <el-button size="small" type="primary" @click="openDrawer()">发起审批</el-button>
          <el-button v-if="(!remodifyId && !reapplyId) || createNew" size="small" type="info" @click="submit(SUBMIT_TYPE.DRAFT)">保存草稿</el-button>
          <el-button class="cancel-btn-style" size="small" @click="toBack">返回</el-button>
        </div>
      </fixed-pagination>
    </div>
  </div>
</template>

<script>
// components
import AuditProcess from '@/components/Common/auditProcess';
import explanation from '@/components/Common/explanation';
import applyInfo from './module/applyInfo';
import customerInfo from './module/customerInfo';
import adjustContent from './module/adjustContent';
import adjustedInfo from './module/adjustedInfo';
// api
import { clientAdjustmentformSubmit, clientAdjustmentDetail, clientAdjustmentCreate, editClientAdjustment, queryAdjustedContent } from '@/api/customer';
import { processManagementDetail } from '@/api/legal';
import { getDepartmentAll } from '@/api/config';
// mixins
import mobileCreate from '@/mixins/mobileCreate';
import processCreate from '@/mixins/processCreate';
// tools
import { SUBMITTYPE as SUBMIT_TYPE } from '@/utils/const/cost';
import { FIXED_PROCESS_TYPE } from '@/utils/const/process';
import { createAuditStructure } from '@/utils/aduitor';
import ElMessage from '@/utils/message';
import { isContained } from '@/utils/tools';
import { mapState } from 'vuex';
export default {
  components: {
    AuditProcess,
    explanation,
    applyInfo,
    customerInfo,
    adjustContent,
    adjustedInfo
  },
  mixins: [mobileCreate, processCreate],
  data() {
    return {
      isEdit: false,
      SUBMIT_TYPE,
      FIXED_PROCESS_TYPE,
      loading: false,
      pageLoading: false,
      remodifyId: null,
      reapplyId: null,
      createNew: 0,
      applyInfo: {
        proposerObj: {},
        avatar: '',
        proposerId: null, // 申请人
        proposer: null, // 申请人名字
        proposerDepartmentId: null, // 申请部门
        rangeList: [], // 申请范围
        attachment: [] // 附件
      }, // 申请信息
      customerInfo: {}, // 当前客户信息,
      adjustedInfo: {
        customerLevel: '',
        loanQuota: '',
        loanPeriod: null
      }, // 调整后客户信息
      adjustContent: {},
      explanationObj: {
        content: '',
        styConfig: ''
      }, // 审批说明
      oldAuditInfo: null, // 保存旧流程用于比较，修改的情况需要判断流程是否发生变动
      processDetail: null,
      rangeList: [],
      clientId: null,
      defaultCustomerName: '',
      adjustLoading: false,
      auditInfo: {
        activeTime: null,
        isSigner: 0,
        countersignSet: 0,
        process: [],
        senders: [],
        id: null
      } // 流程信息
    };
  },
  computed: {
    ...mapState({
      'device': state => state.app.device,
      'userInfo': state => state.user.userInfo
    })
  },
  created() {
    const id = this.$route.params.id;
    this.createNew = Number(this.$route.query.createNew) || 0;
    const remodifyId = this.$route.query.remodifyId; // 修改
    const reapplyId = this.$route.query.reapplyId; // 重新申请
    this.remodifyId = remodifyId;
    this.reapplyId = reapplyId;
    this.queryDeptTreeList();
    this.setCustomerDefaultInfo();
    if (id) {
      this.id = id;
      this.isEdit = true;
      this.getData();
      this.reapplyId && this.getExplanation();
    } else {
      this.isEdit = false;
      this.getExplanation();
    }
  },
  methods: {
    // 从销售客户/渠道订单跳转过来，回填数据
    async setCustomerDefaultInfo() {
      const { applyType, customerId, customerName } = this.$route.query;
      this.$nextTick(() => {
        if (applyType) {
          this.$refs['applyInfoRef'].applyInfo['rangeList'] = [Number(applyType)];
          this.rangeList = [Number(applyType)];
        }
        if (customerId) {
          this.$refs['customerInfoRef'].customerId = Number(customerId);
          this.clientId = Number(customerId);
          this.defaultCustomerName = customerName;
          this.$refs['customerInfoRef'].onClientChange(customerId);
        }
      });
    },
    openDrawer() {
      const promise = [];
      promise.push(this.$refs['applyInfoRef'].validateForm());
      promise.push(this.$refs['customerInfoRef'].validateForm());
      promise.push(this.$refs['adjustContentRef'].validateForm());
      Promise.all(promise).then(() => { // 表单校验通过，则仅提交供应商表单部分，不提交流程信息，用来获取最新流程
        this.getProcessDetail();
      }).catch((e) => {
        console.log(e);
        ElMessage.warning('请检查信息是否填写完整');
      });
    },
    submit(submitType = SUBMIT_TYPE.SUBMIT, senders = []) { // 1草稿 2保存提交 3重新提交
      this.modifySenders = senders;// 存到mixins
      const params = this.getFormData();
      params.submitType = submitType;
      params.isEditAudit = !!(this.remodifyId && this.isRefresh); // 修改时，流程被编辑或者更新
      params.auditInfo = this.auditInfo;
      if (this.createNew) {
        delete params.id;
      }
      if (this.isModifyForm) { // 节点修改走编辑的逻辑
        this.handleModifyData(params);
        this.edit(params);
        return;
      }
      const msg = submitType === SUBMIT_TYPE.DRAFT ? '请确认是否保存草稿' : '请确认是否发起审批';
      this.$confirm(msg, '', {
        confirmButtonText: '确定', type: 'warning', showClose: false,
        center: true, iconClass: 'charge-icon', customClass: 'del-message del-message-cancel'
      }).then(() => {
        if (this.reapplyId || !this.isEdit) {
          this.add(params);
        } else {
          this.handleModifyData(params);
          this.edit(params);
        }
      });
    },
    add(params) {
      if (this.reapplyId && !this.createNew) params.submitType = SUBMIT_TYPE.RESUBMIT;
      clientAdjustmentCreate(params).then(res => {
        if (res.code === 200) {
          ElMessage.success(params.submitType === SUBMIT_TYPE.DRAFT ? '保存成功' : '发起成功');
          if (res.data.id && res.data.processId) {
            this.$router.push({
              name: 'customerAdjustmentDetail',
              query: {
                id: res.data.id,
                processId: res.data.processId
              },
              params: {
                id: res.data.id
              }
            });
          } else {
            this.toBack();
          }
        } else {
          ElMessage.error(res.message);
        }
      }).catch(err => {
        if (err.code === 502) {
          this.$refs['auditProcess'].setShowRefresh(true);
        }
        this.loading = false;
      });
    },
    edit(params) {
      params.id = this.id;
      editClientAdjustment(params).then(res => {
        if (res.code === 200) {
          ElMessage.success(params.submitType === SUBMIT_TYPE.DRAFT ? '保存成功' : '发起成功');
          if (res.data.processId) {
            this.$router.push({
              name: 'customerAdjustmentDetail',
              query: { id: params.id, processId: res.data.processId }
            });
          } else {
            this.toBack();
          }
        } else {
          ElMessage.error(res.message);
        }
      }).catch(err => {
        if (err.code === 502) {
          this.$refs['auditProcess'].setShowRefresh(true);
        }
        if (err.code === 505) { // 节点修改跳转详情
          this.nodeModifyJumpDetail({ routeName: 'customerAdjustmentDetail', params: {}, query: { id: this.id, processId: this.remodifyId }});
        }
        this.loading = false;
      });
    },
    getProcess() {
      this.getProcessDetail(true);
      this.isRefresh = true;
    },
    getFormData() {
      const params = this.$refs.applyInfoRef.getFormData();
      const customerInfo = this.$refs.customerInfoRef.getFormData();
      const { customerId, clientName, sale, clientStatusStr, clientGrade, oweData, accountPeriod, levelColor } = customerInfo;
      const adjustContent = this.$refs.adjustContentRef.getFormData();
      const clientLevelId = adjustContent.id;
      if (adjustContent.quotaApplication) adjustContent.quotaApplication = Number(adjustContent.quotaApplication);
      if (adjustContent.payPeriodApplication) adjustContent.payPeriodApplication = Number(adjustContent.payPeriodApplication);
      delete params.rangeList;
      delete params.proposerObj;
      return { ...params, customerId, clientLevelId, customer: clientName, sale, customerStatus: clientStatusStr, sourceCustomerLevelColor: levelColor, sourceCustomerLevel: clientGrade, loanQuota: oweData && oweData.availableAmount ? oweData.availableAmount : null, loanPeriod: accountPeriod, ...adjustContent };
    },
    queryDeptTreeList() {
      getDepartmentAll().then(res => {
        if (res.code === 200) {
          this.deptTreeList = res.data;
        }
      });
    },
    queryAdjustedInfo() {
      const customerInfo = this.$refs.customerInfoRef.getFormData();
      const adjustContent = this.$refs.adjustContentRef.getFormData();
      const params = {
        customerId: customerInfo.customerId,
        sourceCustomerLevel: customerInfo.clientGrade || null,
        ...adjustContent
      };
      if (customerInfo.customerId && _.values(params).some(v => !!v)) {
        this.adjustLoading = true;
        queryAdjustedContent(params).then(res => {
          if (res.code === 200) {
            this.adjustedInfo = res.data;
          }
          this.adjustLoading = false;
        }).catch(err => {
          console.error(err.message);
          this.adjustLoading = false;
        });
      }
    },
    setClientInfo(data) {
      this.$set(this.customerInfo, 'customerId', data.id);
      this.queryAdjustedInfo();
    },
    onRangeChange(data) {
      this.rangeList = data;
    },
    handleEditData(data) {
      const detailData = _.cloneDeep(data);
      const {
        proposerDepartmentId,
        rangeList,
        description,
        attachment,
        proposer,
        proposerId,
        creatorId,
        creator,
        quotaApplication,
        customerLevelId,
        customerLevel,
        loanQuota,
        loanPeriod,
        payPeriodApplication
      } = detailData;
      this.applyInfo = {
        proposerDepartmentId,
        rangeList,
        description,
        attachment,
        proposer,
        proposerId,
        creator: this.reapplyId ? this.userInfo.userName : creator,
        creatorId: this.reapplyId ? this.userInfo.id : creatorId,
        applicantId: proposerId,
        proposerObj: {
          id: proposerId,
          userName: proposer
        },
        creatorObj: {
          id: this.reapplyId ? this.userInfo.id : creatorId,
          userName: this.reapplyId ? this.userInfo.userName : creator
        }
      };
      this.clientId = detailData.customerInfo ? detailData.customerInfo.customerId : null;
      this.defaultCustomerName = detailData.customerInfo ? detailData.customerInfo.customerName : null;
      this.rangeList = rangeList;
      this.adjustContent = { customerLevelId, quotaApplication, levelAccountPeriod: loanPeriod, levelAmount: loanQuota, payPeriodApplication };
      this.adjustedInfo = {
        customerLevel,
        loanQuota: quotaApplication ? `${quotaApplication + loanQuota}/${quotaApplication + loanQuota}` : `${loanQuota}/${loanQuota}`,
        loanPeriod: payPeriodApplication ? (payPeriodApplication + loanPeriod) : loanPeriod
      };
    },
    getData(id = this.id) {
      this.pageLoading = true;
      clientAdjustmentDetail(id).then(res => {
        if (res.code === 200) {
          this.handleEditData(res.data);
          if (res.data.auditInfo && !this.reapplyId) {
            this.oldAuditInfo = Object.assign({}, res.data.auditInfo);
            this.auditInfo = JSON.parse(JSON.stringify(res.data.auditInfo));
            this.processDetail = JSON.parse(JSON.stringify(res.data.auditInfo));
          }
          if (this.applyInfo.proposerId) {
            this.applyInfo.proposerObj = {
              id: this.applyInfo.proposerId,
              userName: this.applyInfo.proposer,
              avatar: this.applyInfo.avatar
            };
          }
          if (res.data.isDraft || !this.auditInfo || !this.auditInfo.id || this.reapplyId) {
            this.getExplanation();
          }
          this.$nextTick(() => {
            this.setFormData(res.data);
            this.pageLoading = false;
          });
          this.version = Number(res.data.version) || 0;// 当前详情版本，version存在mixins
        }
      }).catch(_ => {
        this.pageLoading = false;
      });
    },
    // 回填表单数据
    setFormData(data) {
      data.proposerId && (this.$refs['applyInfoRef'].defaultProposer = [{ id: data.proposerId, userName: data.proposer }]);
    },
    getExplanation() {
      processManagementDetail({ id: 3527, type: FIXED_PROCESS_TYPE.CUSTOMER_ADJUSTMENT }).then(res => {
        // 审批说明
        const data = res.data[0];
        this.explanationObj.content = data.explanation || '';
        this.explanationObj.styConfig = data.styConfig || '';
      }).catch(err => {
        console.log(err);
      });
    },
    // 获取流程详情
    getProcessDetail(isRefresh = false) {
      this.loading = true;
      const params = this.getFormData();
      // params.type = 23;
      clientAdjustmentformSubmit(params).then(res => {
        this.loading = false;
        if (res.code === 200) {
          const data = res.data;
          if (this.remodifyId && !isRefresh) {
            this.isProcessChange(data, this.oldAuditInfo) && this.$refs['auditProcess'].setShowRefresh(true);
          } else {
            this.processDetail = data;
            this.auditInfo.activeTime = data.activationTime;
            this.auditInfo.id = data.id;
            const applyInfo = this.$refs.applyInfoRef.getFormData();
            this.auditInfo.process = createAuditStructure(data.process, this.userInfo, applyInfo.proposerObj);
            this.auditInfo.senders = data.senderDiyUserList || [];
          }
          if (this.remodifyId && isRefresh) { // 修改刷新保存刷新后流程用于对比
            this.oldAuditInfo = Object.assign({}, data);
            this.oldAuditInfo.process.forEach(el => {
              this.oldAuditInfo.templateNodeId = el.id;
            });
            this.oldAuditInfo.activeTime = data.activationTime * 1000;
          }
          this.$refs['auditProcess'].openDrawer();
        } else {
          this.$message.error(res.message);
        }
      }).catch(_ => {
        this.loading = false;
      });
    },
    isProcessChange(nowAuditInfo = {}, oldAuditInfo = {}) {
      if (nowAuditInfo.activationTime !== (oldAuditInfo.activeTime / 1000)) {
        return true;
      }
      const nowProcessIds = nowAuditInfo && nowAuditInfo.process.map(el => el.id) || [];
      const oldProcessIds = oldAuditInfo && oldAuditInfo.process.map(el => el.templateNodeId) || [];
      return !isContained(nowProcessIds, oldProcessIds);
    },
    toBack() {
      const { applyType, customerId, from } = this.$route.query;
      if (applyType && customerId && from !== 'list') {
        this.$router.push({
          name: 'detailCustomer',
          params: { customerId }
        });
      } else {
        this.$router.push({
          name: 'customerAdjustment'
        });
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.adjustment-create-wrap {
  margin: 16px;
  background-color: #fff;
  min-height: calc(100vh - 64px);
  .page-container {
    padding: 24px 24px 0;
    &.pb55 {
      padding-bottom: 55px;
    }
  }
}
</style>
